package com.signway.swmediaplayerdemo;

import static com.signway.swmediaplayerdemo.MainActivity.hideBottomUIMenu;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.signway.SignwayManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.SubtitleTest;
import com.signway.ffmpeg.FFmpeg;
import com.signway.swmediaplayer.SWMediaPlayer;
import com.signway.swmediaplayer.utils.SystemProperties;
import com.signway.swmediaplayerdemo.databinding.ActivityListSwitchDoubleBinding;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ListSwitchDoubleActivity extends AppCompatActivity {
    private static final String TAG = ListSwitchDoubleActivity.class.getName();
    private ActivityListSwitchDoubleBinding binding;
    private SurfaceView mSurfaceView4K;
    private SurfaceView mSurfaceView2K;

    private SWMediaPlayer mSWMediaPlayer;

    private boolean is2K = true;
    private final String VideoPath2K = Environment.getExternalStorageDirectory().getPath() + "/testmp5/3_v_25_1080.mp4";
//    private final String VideoPath2K = "/mnt/usb/storage5-1/YRZX_4K.mp4";
//    private final String VideoPath2K = Environment.getExternalStorageDirectory().getPath() + "/testmp4/2_v_25.mp4";
    private final String VideoPath4K = Environment.getExternalStorageDirectory().getPath() + "/testmp5/2_v_25_1080.mp4";

    private int surfaceLayoutIndex = 0;
    private SurfaceHolder mCurSurfaceHolder = null;
    private static final int SURFACE_CREATE = 0;
    private static final int SHOW_IMAGE = 1;
    private static final int SWITCH_VIDEO = 2;

    private Bitmap bitmap4K = null;
    private Bitmap bitmap2K = null;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SURFACE_CREATE:
                    if (mSurfaceView2K != null && mCurSurfaceHolder == mSurfaceView2K.getHolder()) {
                        if (mSurfaceView4K != null) {
                            binding.surfaceLayout.removeView(mSurfaceView4K);
                            surfaceLayoutIndex--;
                            mSurfaceView4K = null;
                        }
                    } else {
                        if (mSurfaceView2K != null) {
                            binding.surfaceLayout.removeView(mSurfaceView2K);
                            surfaceLayoutIndex--;
                            mSurfaceView2K = null;
                        }
                    }
                    break;
                case SHOW_IMAGE:
                    new Thread(() -> {
                        Bitmap bitmap = null;
                        if (is2K) {
                            if (bitmap2K == null) {
                                runOnUiThread(() -> {
//                                    binding.time.setVisibility(View.GONE);
                                });
                                /* judge whether capture mode to use: vendor.mstar.screencap.mode
                                 * 0: capture osd + video (default);
                                 * 1: only video;
                                 * 2: only osd.
                                 */
                                bitmap2K = sm.shotScreen(0, 1);
                                Log.d(TAG, "shotScreen start");
                                Log.d(TAG, "shotScreen end");
//                                savebitmap(bitmap4K, "/sdcard/bitmap4K.bmp");
                                runOnUiThread(() -> {
//                                    binding.time.setVisibility(View.VISIBLE);
                                });
                            }
                            bitmap = bitmap2K;
                        } else {
                            if (bitmap4K == null) {
                                runOnUiThread(() -> {
//                                    binding.time.setVisibility(View.GONE);
                                });
                                Log.d(TAG, "shotScreen start");
                                bitmap4K = sm.shotScreen(0, 1);
                                Log.d(TAG, "shotScreen end");
//                                savebitmap(bitmap4K, "/sdcard/bitmap4K.bmp");
                                runOnUiThread(() -> {
//                                    binding.time.setVisibility(View.VISIBLE);
                                });
                            }
                            bitmap = bitmap4K;
                        }

                        if (bitmap == null) {
                            Log.d(TAG, "shotScreen error.");
                            return;
                        }

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            Log.d(TAG, "bitmap " + bitmap.getWidth() + ", " + bitmap.getHeight() + ", " + bitmap.getColorSpace());
                        }

                        final Bitmap finalBitmap = bitmap;
                        runOnUiThread(() -> {
                            binding.image.setImageBitmap(finalBitmap);
                            Log.d(TAG, "show decodeFile end.");
                            binding.image.setVisibility(View.VISIBLE);
                            Log.d(TAG, "show bitmap end.");
                            mHandler.sendEmptyMessage(SWITCH_VIDEO);
                        });
                    }).start();
                    break;
                case SWITCH_VIDEO:
                    switchMedia();
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                Log.d(TAG, "KEYCODE_VOLUME");
                return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityListSwitchDoubleBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        hideBottomUIMenu(this);

        sm = getSystemService(SignwayManager.class);

        mSWMediaPlayer = new SWMediaPlayer();
        mSWMediaPlayer.setOnPreparedListener(mOnPreparedListener);
        mSWMediaPlayer.setOnInfoListener(mOnInfoListener);
        mSWMediaPlayer.setOnCompletionListener(mOnCompletionListener);

        switchMedia();

        sm = getSystemService(SignwayManager.class);
        WindowManager windowManager = getWindow().getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(metrics);
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        Log.d(TAG, "width " + width + ", height " + height);
        mSubtitleTest.init(sm, width, height);
    }

    private SubtitleTest mSubtitleTest = new SubtitleTest();

    @Override
    protected void onStop() {
        super.onStop();
        mHandler.removeCallbacksAndMessages(null);
        mSWMediaPlayer.release();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSubtitleTest.release();
    }

    private void switchMedia() {
        if (is2K) {
            initPlayer2K();
            is2K = false;
        } else {
            initPlayer4K();
            is2K = true;
        }
        binding.init.setVisibility(View.GONE);
    }

    private SignwayManager sm;

    private SWMediaPlayer.OnCompletionListener mOnCompletionListener =
            (mp, lastRenderTimestampNs) -> SWMediaPlayer.MEDIA_COMPLETION_STOP;
    private SWMediaPlayer.OnPreparedListener mOnPreparedListener =
            mp -> mp.start();
    private SWMediaPlayer.OnInfoListener mOnInfoListener = (mp, what, extra) -> {
        switch (what) {
            case SWMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                binding.image.setVisibility(View.GONE);
                break;
            case SWMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_END:
                mHandler.sendEmptyMessageDelayed(SHOW_IMAGE, 40);
                break;
        }
        return true;
    };

    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void initPlayer4K() {
        if (mSurfaceView4K == null) {
            mSurfaceView4K = new SurfaceView(this);
            mSurfaceView4K.setLayoutParams(new RelativeLayout.LayoutParams(2160, 3840));
            binding.surfaceLayout.addView(mSurfaceView4K, surfaceLayoutIndex++);
        }

//        if (mSurfaceView2K != null) {
//            binding.surfaceLayout.removeView(mSurfaceView2K);
//            surfaceLayoutIndex--;
//            mSurfaceView2K = null;
//        }

        mSurfaceView4K.getHolder().setFormat(PixelFormat.TRANSPARENT);
        mSurfaceView4K.getHolder().addCallback(new SurfaceCallBack(this, mSWMediaPlayer));
        mSurfaceView4K.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

//        if (mSWMediaPlayer != null) {
//            mSWMediaPlayer.release();
//        }
//        mSWMediaPlayer = new SWMediaPlayer();
//        mSWMediaPlayer.setOnPreparedListener(mOnPreparedListener);
//        mSWMediaPlayer.setOnInfoListener(mOnInfoListener);
//        mSWMediaPlayer.setOnCompletionListener(mOnCompletionListener);

        try {
            mSWMediaPlayer.reset();
            mSWMediaPlayer.setDataSource(VideoPath4K);
            mSWMediaPlayer.setDisplay(mSurfaceView4K.getHolder());
            Log.d(TAG,  "mPlayer.getDuration() " + mSWMediaPlayer.getDuration());
        } catch (Exception e) {
            e.printStackTrace();
            mSWMediaPlayer.release();
            Toast.makeText(this, "无法播放", Toast.LENGTH_LONG).show();
        }
    }

    private void initPlayer2K() {
        if (mSurfaceView2K == null) {
            mSurfaceView2K = new SurfaceView(this);
            mSurfaceView2K.setLayoutParams(new RelativeLayout.LayoutParams(2160, 1215));
            binding.surfaceLayout.addView(mSurfaceView2K, surfaceLayoutIndex++);
        }

//        if (mSurfaceView4K != null) {
//            binding.surfaceLayout.removeView(mSurfaceView4K);
//            surfaceLayoutIndex--;
//            mSurfaceView4K = null;
//        }

        mSurfaceView2K.getHolder().setFormat(PixelFormat.TRANSPARENT);
        mSurfaceView2K.getHolder().addCallback(new SurfaceCallBack(this, mSWMediaPlayer));
        mSurfaceView2K.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

//        if (mSWMediaPlayer != null) {
//            mSWMediaPlayer.release();
//        }
//        mSWMediaPlayer = new SWMediaPlayer();
//        mSWMediaPlayer.setOnPreparedListener(mOnPreparedListener);
//        mSWMediaPlayer.setOnInfoListener(mOnInfoListener);
//        mSWMediaPlayer.setOnCompletionListener(mOnCompletionListener);

        try {
            mSWMediaPlayer.reset();
            mSWMediaPlayer.setDataSource(VideoPath2K);
            mSWMediaPlayer.setDisplay(mSurfaceView2K.getHolder());
            Log.d(TAG,  "mPlayer.getDuration() " + mSWMediaPlayer.getDuration());
        } catch (Exception e) {
            e.printStackTrace();
            mSWMediaPlayer.release();
            Toast.makeText(this, "无法播放", Toast.LENGTH_LONG).show();
        }
    }

    private class SurfaceCallBack implements SurfaceHolder.Callback {

        public SurfaceCallBack(Context context, SWMediaPlayer player) {
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mCurSurfaceHolder = holder;
            Log.d(TAG, "surfaceCreated " + holder.toString());
            try {
                mSWMediaPlayer.prepare();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }

            if (mSurfaceView2K != null && mCurSurfaceHolder == mSurfaceView2K.getHolder()) {
                if (mSurfaceView4K != null) {
                    binding.surfaceLayout.removeView(mSurfaceView4K);
                    surfaceLayoutIndex--;
                    mSurfaceView4K = null;
                }
            } else {
                if (mSurfaceView2K != null) {
                    binding.surfaceLayout.removeView(mSurfaceView2K);
                    surfaceLayoutIndex--;
                    mSurfaceView2K = null;
                }
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            Log.d(TAG, "surfaceChanged width " + width + ", height" + height);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.d(TAG, "surfaceDestroyed");
        }
    }
}